# 封装一个登录判断的 Mixin 扩展类
from django.http import JsonResponse


def login_required(view_func):
    def wrapper(request, *args, **kwargs):
        # 判断是否登录
        if request.user.is_authenticated:
            # 用户已登录
            return view_func(request, *args, **kwargs)
        else:
            # 用户未登录
            return JsonResponse({'code': 400,
                                 'message': '用户未登录!'})

    return wrapper


class LoginRequiredMixin(object):
    """登录判断的 Mixin 扩展类"""
    @classmethod
    def as_view(cls, **initkwargs):
        # View 类中 as_view 方法返回 view
        view_func = super().as_view(**initkwargs)

        return login_required(view_func)
